package cn.dkdoo.mongodb.service;

import cn.dkdoo.bean.entity.TestTraUser;
import cn.dkdoo.bean.vo.*;
import cn.dkdoo.mongodb.config.MongodbConfig;
import cn.dkdoo.mongodb.repository.MongodbRepository;
import cn.dkdoo.utils.annotation.DkdTransactional;
import cn.dkdoo.utils.entity.BaseResponse;
import cn.dkdoo.utils.templateDefault.mongo.DefaultMongoTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by Nicky.Tang on 2021/5/12 11:00 下午
 *
 * @since 02.12.10
 */
@Service
@DkdTransactional
public class MongodbService {

    @Autowired
    MongodbRepository mongodbRepository;

    @Resource(name = MongodbConfig.defaultMongoTemplate)
    DefaultMongoTemplate dkdMongoTemplate;

    public BaseResponse add(AddRequest request) {
        AddResponse response = new AddResponse();
        mongodbRepository.add(request.getData());
        response.buildSuccess();
        return response;
    }

    public BaseResponse update(UpdateRequest request) {
        BaseResponse response = new BaseResponse();
        mongodbRepository.update(request.getId(), request.getName());
        response.buildSuccess();
        return response;
    }

    public BaseResponse updateSelf(UpdateRequest request) {
        BaseResponse response = new BaseResponse();
        TestTraUser testTraUserOld = mongodbRepository.findRol(request.getId());//find的后，直接加入回滚列表

        // do some other business code ...

        //手动存入待回滚数据（todo 有n个字段，但是只修改了某几个字段 如何减少修改量）
        //dkdMongoTemplate.addUpdateRollbackData(testTraUserOld, TestTraUser.class);//findRol已经加入了回滚列表
        mongodbRepository.updateSelf(request.getId(), request.getName());
        response.buildSuccess();
        return response;
    }

    public BaseResponse updateMulti(UpdateMultiRequest request) {
        BaseResponse response = new BaseResponse();
        List<String> ids = request.getIds();
        List<TestTraUser> testTraUserOlds = mongodbRepository.find(ids);
        dkdMongoTemplate.addOneRollbackData(testTraUserOlds, TestTraUser.class);
        for (String id : ids) {
            // do some other business code ...

            mongodbRepository.updateSelf(id,null);
        }
        response.buildSuccess();
        return response;
    }

    public BaseResponse remove(RemoveRequest request) {
        BaseResponse response = new BaseResponse();
        mongodbRepository.remove(request);
        response.buildSuccess();
        return response;
    }
}
